﻿using System;
using System.Linq;
using System.Web.Mvc;
using TeamCityMonitor.Attributes;
using TeamCityMonitor.Manager;

namespace TeamCityMonitor.Controllers
{   
    [DisableCaching]
    public class CustomController : Controller
    {
        private ICustomManager customManager;
        private BuildManager buildManager;

        public CustomController()
        {
            customManager = new CustomManager();
            buildManager = new BuildManager();
        }

        [DisableCaching]
        public ActionResult Index()
        {
            ViewBag.FeedDelay = customManager.GetFeedDelay(); ;
            ViewBag.ScaleToWidth = Properties.Settings.Default.ScaleCustomPicturesTo;

            if(buildManager.HasBuildsToShow())
            {
                return RedirectToAction("Index", "Home");
            }

            return View(customManager.GetCustomModels().First());
        }
        
        [DisableCaching]
        public JsonResult GetCustomEntry()
        {
            try
            {
                return Json(new { success = true, result = customManager.GetCustomModels().First() }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log4net.LogManager.GetLogger("Main").Error("Custom - GetCustomEntries", ex);

                return Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [DisableCaching]
        public JsonResult ShouldRedirect()
        {
            try
            {
                return Json(new { success = buildManager.HasBuildsToShow(), redirect = Url.Action("Index", "Home") }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log4net.LogManager.GetLogger("Main").Error("Custom - ShouldRedirect", ex);

                return Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
    }
}
